from src.core import create_character, delete_character
from src.storage import save_characters, load_characters
from .display import display_all_characters, display_single_character

def show_main_menu():
    """显示主菜单并获取用户选择。
    
    Returns:
        str: 用户的选择，范围是'1'到'5'
    """
    print("\nGame Character Collection Management System")
    print("1. Add a new character")
    print("2. View all characters")
    print("3. View character details")
    print("4. Delete character")
    print("5. Exit the system")
    choice = input("Please select an operation (enter 1-5): ").strip()
    return choice

def handle_create_character(all_chars):
    """处理创建新角色的用户交互和逻辑。
    
    Args:
        all_chars (list): 当前所有角色的列表
        
    Returns:
        list: 更新后的角色列表
    """
    print("\n Add new game character")
    game_name = input("Please enter the game name: ")
    char_name = input("Please enter the character name: ")
    char_type = input("Please enter the character type: ")
    return create_character(all_chars, game_name, char_name, char_type)

def handle_view_character_detail(all_chars):
    """处理查看角色详情的用户交互和逻辑。
    
    Args:
        all_chars (list): 当前所有角色的列表
    """
    if len(all_chars) == 0:
        print("No characters to view, please add a character first!")
        return
    display_all_characters(all_chars)
    target_id = input("Please enter the character ID to view details: ").strip()
    # Find the character with the target ID
    char_to_view = None
    for char in all_chars:
        if char['id'] == target_id:
            char_to_view = char
            break
    if char_to_view:
        display_single_character(char_to_view)
        input("\nPress Enter to return to the main menu...")
    else:
        print(f"Character with ID {target_id} not found.")
        input("Press Enter to continue...")

def handle_delete_character(all_chars):
    """处理删除角色的用户交互和逻辑。
    
    Args:
        all_chars (list): 当前所有角色的列表
        
    Returns:
        list: 更新后的角色列表
    """
    if len(all_chars) == 0:
        print("No characters can be deleted, please add a character first!")
        return all_chars
    display_all_characters(all_chars)
    target_id = input("Please enter the character ID to be deleted: ").strip()
    # Find the character with the target ID
    char_to_delete = None
    for char in all_chars:
        if char['id'] == target_id:
            char_to_delete = char
            break
    if char_to_delete:
        # Show confirmation information including character ID
        print(f"\nAre you sure you want to delete this character?")
        print(f" ID: {char_to_delete['id']}")
        print(f" Game: {char_to_delete['game_name']}")
        print(f" Character: {char_to_delete['char_name']}")
        
        # Ask for user confirmation
        confirm = input("Type 'yes' to confirm deletion, or any other key to cancel: ").lower()
        if confirm == 'yes':
            return delete_character(all_chars, target_id)
        else:
            print("Deletion cancelled.")
            return all_chars
    else:
        print(f"Character with ID {target_id} not found.")
        return all_chars

def run_console_app():
    """运行控制台应用程序的主循环。
    
    加载角色数据，显示主菜单，处理用户选择的操作，并保存更改。
    """
    all_characters = load_characters()    
    while True:
        choice = show_main_menu()
    
        if choice == "1":
            all_characters = handle_create_character(all_characters)
            # Auto-save after creating character
            save_characters(all_characters)
            print("Character saved automatically.")
        elif choice == "2":
            display_all_characters(all_characters)
            input("Press Enter to return to the main menu...")
        elif choice == "3":
            handle_view_character_detail(all_characters)
        elif choice == "4":
            all_characters = handle_delete_character(all_characters)
            # Auto-save after deleting character
            save_characters(all_characters)
            print("Character collection updated and saved automatically.")
        elif choice == "5":
            save_confirm = input("Do you want to save the current characters to a file? (y/n): ").lower()
            if save_confirm == "y":
                save_characters(all_characters)
                print("Save successfully!")
                print("Exit the system, goodbye!")
                break
            elif save_confirm == "n":
                print("Exit the system, goodbye!")
                break
            else : 
                while True:

                    print("Please enter 'y' or 'n'.")
                    save_confirm = input("Do you want to save the current characters to a file? (y/n): ").lower()
                    if save_confirm == "y":
                        save_characters(all_characters)
                        print("Save successfully!")
                        print("Exit the system, goodbye!")
                        break
                    elif save_confirm == "n":
                        print("Exit the system, goodbye!")
                        break
                    else :
                        print("Please enter 'y' or 'n'.")
                
        else:
            print("Input error, please reselect from 1 to 5!")


def main():
    """控制台应用程序的入口函数。
    
    调用run_console_app()函数启动应用程序。
    """
    run_console_app()

if __name__ == "__main__":
    main()
